<?php
function my_og_type( $type ) {
	global $birdbrain_is_singular;
    if ($birdbrain_is_singular) {
        $type = "article";
    } else 
	$type = "blog";
    return $type;
}

//	add_filter( 'opengraph_type', 'my_og_type' );

function display_latest_tweet () {
	require_once(ABSPATH . 'wp-includes/class-snoopy.php');
	$tweet   = get_option("lasttweet");
	$url  = "http://twitter.com/statuses/user_timeline/free_thinker.json?count=1";
	if ($tweet['lastcheck'] < ( mktime() - 60 ) ) {
		$snoopy = new Snoopy;
		$result = $snoopy->fetch($url);
		if ($result) {
			$twitterdata   = json_decode($snoopy->results,true);
			$i = 0;
			while ($twitterdata[$i]['in_reply_to_user_id'] != '') {
				$i++;
			}
			$pattern  = '/\@([a-zA-Z]+)/';
			$replace  = '<a href="http://twitter.com/'.strtolower('\1').'">@\1</a>';
			$output   = preg_replace($pattern,$replace,$twitterdata[$i]["text"]);  
			$tweet['lastcheck'] = mktime();
			$tweet['data']    = $output;
			$tweet['rawdata']  = $twitterdata;
			$tweet['followers'] = $twitterdata[0]['user']['followers_count'];
			update_option('lasttweet',$tweet);
			if(contains_a_url($tweet['data'])) {
				$output = MakeItLink::transform($tweet['data']);
			} else
				$output = $tweet['data'];

		} else {
			echo "Twitter API not responding.";
		}
	} else {
		if(contains_a_url($tweet['data'])) {
			$output = MakeItLink::transform($tweet['data']);
		} else
			$output = $tweet['data'];
	}
	echo "".$output."";
}

function contains_a_url($data) {
	$input = $data; 
	$regexp = "#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie";
	if(preg_match($regexp, $input, $matches)) { 
		return TRUE;	
	}
	else {
		return FALSE;
	}

}

class MakeItLink {
    function _link_www( $matches ) {
        $url = $matches[2];
        $url = MakeItLink::cleanURL( $url );
        if( empty( $url ) ) {
            return $matches[0];
        }

        return "{$matches[1]}<a target='_blank' href='{$url}'>{$url}</a>";
    }

    function cleanURL( $url ) {
        if( $url == '' ) {
            return $url;
        }

        $url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
        $url = str_replace( array( "%0d", "%0a" ), '', $url );
        $url = str_replace( ";//", "://", $url );

        /* If the URL doesn't appear to contain a scheme, we
         * presume it needs http:// appended (unless a relative
         * link starting with / or a php file).
         */
        if(
            strpos( $url, ":" ) === false
            && substr( $url, 0, 1 ) != "/"
            && !preg_match( "|^[a-z0-9-]+?.php|i", $url )
        ) {
            $url = "http://{$url}";
        }

        // Replace ampersans and single quotes
        $url = preg_replace( "|&([^#])(?![a-z]{2,8};)|", "&#038;$1", $url );
        $url = str_replace( "'", "&#039;", $url );

        return $url;
    }

    function transform( $text ) {
        $text = " {$text}";

        $text = preg_replace_callback(
            '#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is',
            array( 'MakeItLink', '_link_www' ),
            $text
        );

        $text = preg_replace( '#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $text );
        $text = trim( $text );

        return $text;
    }

}


function tweet_track($long_url) {
	$analytics = '?utm_campaign=Twitter-Analytics-Blogpost&utm_source=twitter&utm_medium=social-media';
	return  $long_url.$analytics;
}

function social_tools_top_track($long_url) {
	$analytics = '?utm_campaign=Social-Top-Blogpost&utm_source=facebuzztweet&utm_medium=social-media';
	return  $long_url.$analytics;
}

function social_tools_bottom_track($long_url) {
	$analytics = '?utm_campaign=Social-Bottom-Blogpost&utm_source=facebuzztweet&utm_medium=social-media';
	return  $long_url.$analytics;
}

//	add_filter( 'yourls_blog_post_url', 'tweet_track' );
//	add_filter( 'sttop_blog_post_url', 'social_tools_top_track' );
//	add_filter( 'stbottom_blog_post_url', 'social_tools_bottom_track' );

function twitter_anywhere_hover_cards()
{
	echo '<script type="text/javascript">';
	echo 'twttr.anywhere(onAnywhereLoad);';
	echo 'function onAnywhereLoad(twitter) { twitter.hovercards(); }';
	echo '</script>';
}


//		add_action("hybrid_before_html", "twitter_anywhere_hover_cards");
//
function link_unit_after_page_nav() {
if(!is_user_logged_in()) {
?>
	<div id="linkunit_pagenav_container">
		<div id="linkunit_pagenav">
			<script type="text/javascript"><!--
			google_ad_client = "pub-3505281667688210";
			/* Humbug Navbar 468x15, created 8/23/10 */
			google_ad_slot = "0060324496";
			google_ad_width = 468;
			google_ad_height = 15;
			//-->
			</script>
			<script type="text/javascript"
			src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
			</script>
		</div>
	</div>
<?php
	}
}

//	add_action( 'hybrid_after_page_nav', 'link_unit_after_page_nav' );
function add_above_primary_asides() {
	if (is_sidebar_active('aboveprimleft')) { 
		echo '<div id="aboveprimleft" class="aside">';
			dynamic_sidebar('aboveprimleft');
		echo '</div>';
	}
	if (is_sidebar_active('aboveprimright')) { 
		echo '<div id="aboveprimright" class="aside">';
			dynamic_sidebar('aboveprimright');
		echo '</div>';
	}
}

//	add_action('hybrid_after_container', 'add_above_primary_asides', 9);
function add_tinymce_to_mblog() {
?>
	<?php if (is_page('mblog') ) { ?>
		<script type="text/javascript" src="<?php echo 
		get_bloginfo('wpurl'); 
		?>/wp-content/tiny_mce/tiny_mce.js"></script>

		<script type="text/javascript">

		tinyMCE.init({

		mode : "textareas",

		theme : "advanced"

		});
		</script>
	<?php } ?>
<?php
}

//	add_action('hybrid_after_html', 'add_tinymce_to_mblog');
//
function add_tertiary_aside() {
	if (is_sidebar_active('tertiary')) { 
		echo '<div id="tertiary" class="aside">';
			dynamic_sidebar('tertiary');
		echo '</div>';
	}
}

//	add_action('hybrid_after_container', 'add_tertiary_aside', 11);
function add_tweetboard_code () { 
?>
	<script type="text/javascript"> 
	var _tbdef = {user: 'free_thinker'};
	(function(){
	var d = document;var tbjs = d.createElement('script'); tbjs.type = 'text/javascript';
	tbjs.async = true; tbjs.src = 'http://tweetboard.com/tb.js'; var tbel = d.getElementsByTagName('body')[0];
	if(!tbel) tbel = d.getElementsByTagName('head')[0]; tbel.appendChild(tbjs);
	})();
	</script>
<?php
}


//	add_action('wp_footer', 'add_tweetboard_code');

function add_subscribe_without_commenting () {
	if ( comments_open() )
		show_manual_subscription_form();
}


//	add_action ('hybrid_after_comment_form', 'add_subscribe_without_commenting');
function add_digg_code() {
?>
<script type="text/javascript">
(function() {
var s = document.createElement('SCRIPT'), s1 = document.getElementsByTagName('SCRIPT')[0];
s.type = 'text/javascript';
s.async = true;
s.src = 'http://widgets.digg.com/buttons.js';
s1.parentNode.insertBefore(s, s1);
})();
</script>
<?php
}

//	add_action('wp_footer', 'add_digg_code');
//
function twitter_anywhere_enqueue_script() {
	global $twitter_api_key;
	global $social_networking_tools_enabled;
	global $birdbrain_is_admin;
	if ( $social_networking_tools_enabled == 1  && !$birdbrain_is_admin)
		wp_enqueue_script("twitter-anywhere", "http://platform.twitter.com/anywhere.js?id={$twitter_api_key}&v=1");
}

//add_action('wp_head', 'twitter_anywhere_enqueue_script',2);

function add_tweetbox() {
	global $birdbrain_is_single;
	if ( $birdbrain_is_single && !is_preview() ) {
	global $post;
	$id = $post->ID;
	$shorturl = wp_ozh_yourls_geturl( $id );
	$title = $post->post_title;
	$twitterid = "@free_thinker";
	$content = $title . " " . $shorturl . " " . $twitterid;
?>
	<div id="tbox"></div>
	<script type="text/javascript">

			  twttr.anywhere(function (T) {

			    T("#tbox").tweetBox({
			      height: 45,
			      width: 616,
			      defaultContent: "<?php echo $content ?>",
					label: "Shout!"
				});

		  });

	</script>
<?php
	}
			
}

if($social_networking_tools_enabled == 1) {
	//add_action('hybrid_after_entry', 'add_tweetbox', 12);
}

function add_book_menu() {
  $menu = file_get_contents('/home/humbug/humbug.in/docs/menu-blog.html');
  echo "<div id='bookmenu'><div id='bookmenu-inner'>$menu</div></div>";
}

//add_action('hybrid_before_html', 'add_book_menu', 9);
function add_book_menu_js() {
	wp_enqueue_script( 'supersubs', BIRDBRAIN_DIR_URL . '/js/supersubs.js', array( 'jquery' ), 0.1 );
	wp_enqueue_script( 'superfish', BIRDBRAIN_DIR_URL . '/js/superfish.js', array( 'jquery' ), 0.1 );
	wp_enqueue_script( 'hoverIntent', BIRDBRAIN_DIR_URL . '/js/hoverIntent.js', array( 'jquery' ), 0.1 );
	wp_enqueue_script( 'addBookMenu', BIRDBRAIN_DIR_URL . '/js/addBookMenu.js', array( 'jquery' ), 0.1 );
}

//add_action('hybrid_head', 'add_book_menu_js');
function add_mblog_to_breadcrumb_trail ($breadcrumb) {
	if (is_p2_custom_post_type()) {
		$target = 'rel="home" class="trail-begin">Home</a>';
		$replacement = 'rel="home" class="trail-begin">Home</a> <a href="http://www.humbug.in/mblog/" rel="tag">µblog</a>';
		$str = str_replace($target, $replacement, $breadcrumb);
		return $str;
	}
	return $breadcrumb;
}

//add_filter( 'breadcrumb_trail', 'add_mblog_to_breadcrumb_trail' );
function add_minify_location(){
	if (class_exists('WPMinify')) {?>

<!-- WP-Minify JS -->
<!-- WP-Minify CSS -->

<?php }
}
add_action('wp_head','add_minify_location',99);

function redirect_xmlrpc_to_custom_post_type ($data, $postarr) {
	global $p2_custom_post_type;
	if (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
		$data['post_type'] = $p2_custom_post_type;
	}
	return $data;
}

//add_filter('wp_insert_post_data', 'redirect_xmlrpc_to_custom_post_type', 99, 2);
/*
function redirect_xmlrpc_to_custom_post_type ($data, $postarr) {
	global $p2_custom_post_type;
	if (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
		foreach($postarr['post_category'] as $catid) {
			$catname = get_cat_name($catid);
			$catprefix = substr($catname, 0, 3);
			if ($catprefix == "pt_") {
				$posttype = substr($catname, 3);
				$data['post_type'] = $posttype;
			}
		}
	}
	return $data;
}

//add_filter('wp_insert_post_data', 'redirect_xmlrpc_to_custom_post_type', 99, 2);

function del_posttype_cats($postid) {
	if (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
		$i = 0;
		$catids = array();
		foreach((get_the_category($postid)) as $category) { 
			$catprefix = substr($category->cat_name, 0, 3);
			if ($catprefix != "pt_") {
				$catids[$i] = $category->cat_ID;
				$i++;
			}
		}
		wp_set_post_categories($postid, $catids);
	}
}

//add_action( 'save_post', 'del_posttype_cats');
*/
function webgains_code() {
	echo '<!-- WGCCPTK001 -->'. "\n";
}

function webgains_code_head() {
	echo '<meta property="webgains_code" content="WGCCPTK001"/>'. "\n";
	echo "<meta name='cpalead-verification' content='_-Km7DLytUzwszP7mD9ZKf9Z8m2SI1E95q80PcxCzNK' />" . "\n";
}
add_action('wp_head', 'webgains_code_head');
add_action('wp_footer', 'webgains_code', 1000);

/*
function exclude_category_filter() {
	add_filter('pre_get_posts', 'exclude_category');
}

function exclude_category_filter_end() {
	remove_filter('pre_get_posts', 'exclude_category');
}
*/
function remove_sliding_panel() {
	remove_action( 'hybrid_before_html', 'get_sliding_panel');
}

add_action( 'template_redirect', 'remove_sliding_panel' );


?>
